#include <time.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/select.h>
// ============== 说明 ==============
// 已完成：超时踢出
// 下一步：增加日志功能 
// ============== 宏定义 ==============
#define PORT            9080
#define BUF_SIZE        4096
#define MAX_CLIENTS     10
#define LOG_FILE        "receive_massages.log"

// ============== 宏函数 ==============
#define CHECK_ERROR(cond, msg, cleanup) \
    if(cond) { perror(msg); cleanup; return -1; }
// ============== 结构体 ==============
typedef struct conn_s{          // 用于超时踢出
    int client_fd;
    time_t last_time;
}conn_s;

// ============== 函数声明 ==============
int write_log_entry(int fd, const char *buf, int len);
int send_http_hello(int fd);    // 预留给stm32专用的废话报文，现在暂时用不上
int send_http_response(int fd, const char* content_type, const char *content);
int get_device_id_from_request(const char *http_request);
int send_log(int client_fd);
int clear_log(int client_fd);
void remove_client(fd_set *base_set, struct conn_s *client_fds, int *n_clients, int index);

// ============== 主函数 ==============
int main() {
    // 检查句柄返回
    int ret_check = 0;

    // 创建socket
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    CHECK_ERROR(socket_fd < 0, "socket", NULL);

    // 设置端口复用
    int reuse = 1;
    ret_check = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    CHECK_ERROR(ret_check < 0, "setsockopt", close(socket_fd));

    // 绑定地址
    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_port = htons(PORT),
        .sin_addr.s_addr = INADDR_ANY
    };

    ret_check = bind(socket_fd, (struct sockaddr*)&addr, sizeof(addr));
    CHECK_ERROR(ret_check < 0, "bind", close(socket_fd));

    // 开始监听
    ret_check = listen(socket_fd, MAX_CLIENTS);  // [!] 使用宏定义
    CHECK_ERROR(ret_check < 0, "listen", close(socket_fd));

    printf("Server started on port %d\n", PORT);

    // 创建监听队列
    conn_s client_fds[MAX_CLIENTS] = {0};
    int n_clients = 0;

    // base_set，保存下一次循环要监听的文件描述符集合
    fd_set base_set;
    FD_ZERO(&base_set);
    FD_SET(socket_fd, &base_set);
    FD_SET(STDIN_FILENO, &base_set);

    while (1) {
        // 1. 准备工作：更新下标 | 监听 | 超时踢出
        fd_set read_set;
        FD_ZERO(&read_set);
        memcpy(&read_set, &base_set, sizeof(base_set));

        int max_fd = socket_fd;
        for(int i = 0; i < n_clients; i++){
            if(client_fds[i].client_fd > max_fd){
                max_fd = client_fds[i].client_fd;
            }
        }

        struct timeval tv;
        tv.tv_sec = 10;     // 误差为10秒
        tv.tv_usec = 0;
        ret_check = select(max_fd + 1, &read_set, NULL, NULL, &tv);
        CHECK_ERROR(ret_check < 0, "select", NULL);

        // 2. 处理新链接, accept并添加到client_fds
        if(FD_ISSET(socket_fd, &read_set)){
            // 接受客户端连接
            struct sockaddr_in client_addr;
            socklen_t addr_len = sizeof(client_addr);

            // 监听到新链接
            int new_fd = accept(socket_fd, (struct sockaddr*)&client_addr, &addr_len);

            // 将新链接加入监听，并保存net_fd到list
            if(new_fd < 0){
                perror("accept");
            }
            else if(n_clients < MAX_CLIENTS){
                printf("New client from %s:%d (fd=%d)\n", 
                       inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), new_fd);
                FD_SET(new_fd, &base_set);
                client_fds[n_clients].client_fd = new_fd;
                time(&client_fds[n_clients].last_time);
                n_clients++;
            }
            else{
                close(new_fd);
                printf("Max clients reached!\n");
            }
        }

        // 3. 处理客户端消息
        for(int i = 0; i < n_clients; i++){
//            int client_fd = client_fds[i].client_fd;

            if (FD_ISSET(client_fds[i].client_fd, &read_set)) {
                char buf[BUF_SIZE];
                ssize_t len = recv(client_fds[i].client_fd, buf, sizeof(buf) - 1, 0); // 保留空间给'\0'

                // 3.1 用户已断开链接
                if (len <= 0) {
                    printf("Client %d disconnected\n", client_fds[i].client_fd);

                    remove_client(&base_set, client_fds, &n_clients, i);
                    i--;
//                    FD_CLR(client_fds[i].client_fd, &base_set);   
//                    close(client_fds[i].client_fd);
//                    for(int k = i; k < n_clients; k++){
//                        client_fds[k] = client_fds[k + 1];
//                    }
//
//                    n_clients--;
//                    i--;
                }
                // 3.2 写文件并回复
                else{
                    buf[len] = '\0';
                    printf("From client[fd=%d]:\n%.*s\n", client_fds[i].client_fd, (int)len, buf);

                    // 3.2.1 将收到的内容写到文件
                    int file_fd = open("receive_massages.log", O_WRONLY | O_CREAT | O_APPEND, 0644);
                    if(file_fd >= 0){
                        ret_check = write_log_entry(file_fd, buf, len);
                        CHECK_ERROR(ret_check < 0, "Failed to write_log_entry", NULL);
                        close(file_fd);

                        time(&client_fds[i].last_time);
//                        // 防止STM32透传命令无回复
//                        char *ua_stm32 = strstr(buf, "user-agent: STM32");
//                        if (ua_stm32 != NULL) {
//                            send_http_hello(client_fd);
//                        }
                    }
                    else{
                        perror("open log file failed");
                    }

                    // 3.2.2 回复报文
                    int dev_id = get_device_id_from_request(buf);
                    switch(dev_id) {
                    case 0: 
                        ret_check = send_http_response(client_fds[i].client_fd, "text/plain", "To STM32: Message received and logged");
                        CHECK_ERROR(ret_check < 0, "Fail to send_http_response", NULL);
                        break;
                    case 1:
                    default:    // default是测试用
                        ret_check = send_log(client_fds[i].client_fd);
                        CHECK_ERROR(ret_check < 0, "send_log failed", NULL);

                        remove_client(&base_set, client_fds, &n_clients, i);
                        i--;
                        break;
                    case 2:
                        ret_check = clear_log(client_fds[i].client_fd);
                        CHECK_ERROR(ret_check < 0, "send_log failed", NULL);

                        remove_client(&base_set, client_fds, &n_clients, i);
                        i--;
                        break;
                    }
                }
            }
        }

        // 4. 遍历所有用户, 看是否超时
        time_t  now_time;
        time(&now_time);

        for(int i = 0; i < n_clients; i++){
            if(now_time - client_fds[i].last_time > 60){
                printf("Client %d timed out (60s), kicking...\n", client_fds[i].client_fd);
    
                remove_client(&base_set, client_fds, &n_clients, i);
                i--;
            }
        }

    }

    // 清理
    for(int i = 0; i < n_clients; i++){
        if(client_fds[i].client_fd > 0){
            close(client_fds[i].client_fd);
        }
    }
    close(socket_fd);
    return 0;
}

// ============== 函数实现 ==============

int write_log_entry(int fd, const char *buf, int len){
    // 1. 生成时间戳
    char timestamp[64];
    time_t now = time(NULL);
    struct tm *tm_info = localtime(&now);
    strftime(timestamp, sizeof(timestamp), "[%Y-%m-%d %H:%M:%S]", tm_info);

    // 2. 过滤特殊字符（可选）
    char filtered[len + 1];
    for (int i = 0; i < len; i++) {
        filtered[i] = (buf[i] == '\r' || buf[i] == '\n') ? ' ' : buf[i];
    }
    filtered[len] = '\0';

    // 3. 写入文件
    dprintf(fd, "%s ", timestamp);             // 写入时间
    write(fd, filtered, len);                  // 写入内容
    write(fd, "\n", 1);                        // 换行

    return 0;

}

int send_http_hello(int fd) {
    char body[BUF_SIZE];
    snprintf(body, sizeof(body),
             //             "HTTP/1.1 200 OK\r\n\r\n[\"%s\"]\n",
             "HTTP/1.1 200 OK\r\n\r\n[\"Hello\"]\n");

    int ret_check = send(fd, body, strlen(body), 0);
    CHECK_ERROR(ret_check < 0, "Failed to send_http_hello", NULL);

    return 0;
}

int send_http_response(int fd, const char *content_type, const char *content) {
    char body[BUF_SIZE];
    snprintf(body, sizeof(body),
             //             "HTTP/1.1 200 OK\r\n\r\n[\"%s\"]\n",
             "HTTP/1.1 200 OK\r\n\r\n%s\n", 
             content);

    int ret_check = send(fd, body, strlen(body), 0);
    CHECK_ERROR(ret_check < 0, "Failed to send_http_response", NULL);

    return 0;
}

int get_device_id_from_request(const char*http_request){
    // 1. 查找路径的位置
    const char *path_start = strstr(http_request, "GET /");
    if (!path_start) return -1;

    // 2. 定位数字位置
    const char* num_ptr = path_start + 5;   // "跳过GET /"
    if(!isdigit(*num_ptr)) return -1;

    // 3. 转换ASCII数字为整型
    return *num_ptr - '0';
}

int send_log(int client_fd) {
    //    printf("[test] main.c send_log line274 | open normally\n");

    // 1. 打开文件
    FILE *file = fopen(LOG_FILE, "r");
    if (!file) {
        send_http_response(client_fd, "text/plain", "File error");
        return -1;
    }

    // 2. 准备缓冲区
    char total_buf[BUF_SIZE] = "["; // JSON开始
    char line_buf[256];
    int line_count = 0;

    // 3. 读取文件
    while (fgets(line_buf, sizeof(line_buf), file)) {
        line_count++;
        //        printf("[TEST]main.c line309 |  正在处理第%d行: %s\n", line_count, line_buf);    
        if (strstr(line_buf, "GET /0")) {
            // 原始格式：[2025-05-30 23:09:05] [fd:4]GET /0 HTTP/1.1    [Buzzer:OFF]
            // 目标格式：[2025-05-30 23:09:05]     [Buzzer:OFF]

            // 1. 核心逻辑：提取第一对[]和最后一对[]
            char *first_bracket = strchr(line_buf, '[');
            char *first_end = strchr(line_buf, ']');

            char *last_bracket = strrchr(line_buf, '[');
            char *last_end = strrchr(line_buf, ']');

            // 2. 拼接时间戳 + "    " + Buzzer状态
            if (first_bracket && first_end && last_bracket && last_end) {
                //               printf("[test] main.c send_log line300 | enter strcmp normally\n");  

                // 计算两部分长度
                int first_len = first_end - first_bracket + 1;  // 包括[]
                int last_len = last_end - last_bracket + 1;      // 包括[]

                char temp[256];
                snprintf(temp, sizeof(temp), "\"%.*s    %.*s\"",
                         first_len, first_bracket,
                         last_len, last_bracket);

                //                printf("[test] main.c send_log line316 | finish strcmp normally, the temp is : %s\n", temp);
                // 3. 缓冲区检查
                if (strlen(total_buf) + strlen(temp) + 3 < sizeof(total_buf)) {
                    if (total_buf[1] != '\0') {  // 不是第一个元素（初始为"["）
                        strcat(total_buf, ",");
                    }
                    strcat(total_buf, temp);
                }
                else{
                    //                    printf("[test] main.c line345 | goto break\n");
                    break;
                }

                //                printf("[test] main.c send_log line336 | finish strcmp normally, the temp is : %s\n", temp);
                //                printf("[test] main.c send_log line337 | finish strcmp normally, the total_buf is : %s\n", total_buf);
            }
        }
    }
    // 4. 收尾并发送
    strcat(total_buf, "]");

    // 5. 发送（保持原方式）
    send_http_response(client_fd, "application/json", total_buf);
    fclose(file);
    //    printf("[test] main.c send_log line335 | close normally\n");
    return 0;
}

int clear_log(int client_fd){
    // 1. 打开文件
    int ret_check = truncate(LOG_FILE, 0);
    if(ret_check < 0){
        perror("Clear failed");
    }

    return 0;
}

void remove_client(fd_set *base_set, struct conn_s *client_fds, int *n_clients, int index) {
    printf("Removing client (fd=%d)\n", client_fds[index].client_fd);

    // 1. 从 select 监听集合移除
    FD_CLR(client_fds[index].client_fd, base_set);

    // 2. 关闭 socket
    close(client_fds[index].client_fd);

    // 3. 从数组移除（前移后续元素）
    for (int k = index; k < *n_clients - 1; k++) {
        client_fds[k] = client_fds[k + 1];
    }

    // 4. 更新客户端数量
    (*n_clients)--;
}

